<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class GlobalValidation extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        //调用方法
        $ruleAction = 'getRulesBy'.$this->route()->getActionMethod();
        //如果方法存在就调用
        if (method_exists($this,$ruleAction)){
            return $this->$ruleAction();
        }else{
            //如果不存在就调用其他规则
            return $this->getDefaultRules();
        }
    }

    public function getDefaultRules(){
         return [];
    }

    protected function failedValidation(Validator $validator)
    {
        //获取首个报错信息
        $error = $validator->errors()->first();
        $response = response()->json([
            'code'=>0,
            'msg'=>$error,
            'data'=>[]
            //设置一个提示信息转中文的编码
        ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        throw new HttpResponseException($response);
    }

}
